//
//  JKHomeViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/2.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import MJRefresh

class JKHomeViewController: JKBaseViewController {
    
    var jumpTo: String?
    
    // MARK: - 私有属性
    
    /** cell高度 80 */
    private let tableViewRowH: CGFloat = 80
    
    /** 最新文章数量 */
    private var latestStoryCount: CGFloat = 0
    
    /** 总模型数组 */
    private lazy var stories: [[JKNewsListModel]] = [[JKNewsListModel]]()
    
    /** 今天数据模型数组 */
    private lazy var todayStories: [JKNewsListModel] = [JKNewsListModel]()
    
    /** 日期数组 */
    private lazy var loadedDate = [String]()
    
    /** 今天的日期 */
    private var todayDate = ""
    
    /** 格式化的日期数组 */
    private lazy var fmtDateArr = [String]()
    
    /** 状态栏view */
    private lazy var statusBarView: UIView = {
        
        let statusBarView = UIView(frame: CGRect(x: 0, y: 0, width: JKScreenW, height: JKStatusBarHeight))
        statusBarView.backgroundColor = JKMainColor
        statusBarView.isHidden = true
        view.addSubview(statusBarView)
        
        return statusBarView
    }()
    
    /** 刷新圆圈控件 */
    private lazy var refreshView: JKHomeRefreshProgressView = {
        
        let refreshView = JKHomeRefreshProgressView()
        
        refreshView.backgroundColor = UIColor.clear
        refreshView.frame = CGRect(x: JKScreenW * 0.5 - 30 - 38, y: JKStatusBarHeight + 10, width: 24, height: 24)
        
        view.addSubview(refreshView)
        
        return refreshView
    }()
    
    /** 第一次启动时遮盖的view */
    private lazy var coverView: UIView = {
        
        let coverView = UIView(frame: JKScreenBounds)
        coverView.backgroundColor = UIColor.black
        coverView.isHidden = true
        coverView.alpha = 0.9
        view.addSubview(coverView)
        
        return coverView
    }()
    
    /** 顶部图片轮播view */
    private lazy var mainHeaderView: JKRecycleView = {
       
        let mainHeaderView = JKRecycleView.recycleViewWithFrame(frame: CGRect(x: 0, y: -80, width: JKScreenW, height: JKScreenW * 0.85))
        
        let imgv = UIImageView(image: UIImage(named: "Image_Preview"))
        imgv.frame = mainHeaderView.bounds
        
        let imgCover = UIImageView(image: UIImage(named: "Home_Image_Mask_Plus"))
        imgCover.frame = mainHeaderView.bounds
        imgv.addSubview(imgCover)
        
        mainHeaderView.insertSubview(imgv, at: 0)
        mainHeaderView.delegate = self
        
        return mainHeaderView
    }()
    
    /** 阅读提醒label */
    private lazy var readNoticeLabel: UILabel = {
        
        let label = UILabel()
        
        label.backgroundColor = JKMainColor
        label.text = "       上次看到这里了哦~"
        label.font = UIFont.systemFont(ofSize: 12)
        label.frame = CGRectMake(-138, 0, 138, 25)
        label.isHidden = true
        label.textColor = UIColor.white
        label.layer.cornerRadius = label.height * 0.5
        label.layer.masksToBounds = true
        label.textAlignment = NSTextAlignment.left
        view.addSubview(label)
        
        return label
    }()
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(false, animated: true)
        
        DispatchQueue.once(token: "coverViewOnce") {
            
            JKLog(message: "Do This Once!")
            self.coverView.isHidden = false
            
            UIView.animate(withDuration: 0.75, animations: {
                
                self.coverView.backgroundColor = JKGlobalBgColor
                self.coverView.alpha = 0
                
            }, completion: { (_) in
                
                self.coverView.removeFromSuperview()
            })
        }
        
        if UserDefaults.standard.bool(forKey: JKReadPositionNoticeOffKey) {
            return
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(lastReadNotice(noti:)), name: Notification.Name(JKLastReadIndexNotification), object: nil)
    }
    
    /** 监听阅读位置 */
    @objc private func lastReadNotice(noti: Notification) {
        
        let indexPath = noti.userInfo![JKLastReadIndexKey] as! IndexPath
        
        UIView.animate(withDuration: 0.5) {
            self.tableViewPlain.scrollToRow(at: indexPath, at: UITableViewScrollPosition.none, animated: false)
        }
        
        guard let cell = self.tableViewPlain.cellForRow(at: indexPath) else { return }
        
        let rect = tableViewPlain.convert(cell.frame, to: self.view)
        
        self.readNoticeLabel.y = rect.origin.y + (rect.size.height - self.readNoticeLabel.height) * 0.5
        self.readNoticeLabel.isHidden = false
        
        UIView.animate(withDuration: 0.25, delay: 0.5, options: UIViewAnimationOptions(rawValue: 0), animations: {
            
            self.readNoticeLabel.x = -self.readNoticeLabel.height * 0.5
            
        }) { (_) in
            
            UIView.animate(withDuration: 0.25, delay: 1.25, options: UIViewAnimationOptions(rawValue: 0), animations: {
                
                self.readNoticeLabel.x = -self.readNoticeLabel.width
                
            }) { (_) in
                
                self.readNoticeLabel.isHidden = true
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        mainHeaderViewAddTimer()
        
        weak var weakSelf = self
        
        NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil) { (_) in
            
            weakSelf?.mainHeaderViewAddTimer()
        }
        
        NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidEnterBackground, object: nil, queue: nil) { (_) in
            
            weakSelf?.mainHeaderViewRemoveTimer()
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        mainHeaderViewRemoveTimer()
        
        NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
        NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
        NotificationCenter.default.removeObserver(self, name: Notification.Name(JKLastReadIndexNotification), object: nil)
    }

    // MARK:- 初始化
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if #available(iOS 9.0, *) {
            
            // 注册3DTouch
            if (self.traitCollection.forceTouchCapability == UIForceTouchCapability.available) {
                
                registerForPreviewing(with: self, sourceView: self.tableViewPlain)
            }
            
        } else {
            // Fallback on earlier versions
        }
    }
    
    /** 初始化导航条 */
    internal override func setupNav() {
        
        navTitle = "今日热闻"
        navBackButton.setImage(UIImage(named: "Home_Icon"), for: UIControlState.normal)
        navBackButton.setImage(UIImage(named: "Home_Icon"), for: UIControlState.highlighted)
        navBackButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -3, bottom: 0, right: 0)
        navBgView.alpha = 0
    }
    
    /** 初始化tableView */
    internal override func setupTableView() {
        
        tableViewPlain.rowHeight = tableViewRowH
        tableViewPlain.showsVerticalScrollIndicator = false
        
        let tableHeader = UIView(frame: CGRect(x: 0, y: 0, width: JKScreenW, height: JKScreenW * 0.85 - 120 - 20))
//        tableHeader.backgroundColor = UIColor.red.withAlphaComponent(0.5)
        tableHeader.isUserInteractionEnabled = false
        tableViewPlain.tableHeaderView = tableHeader
        
        tableViewPlain.insertSubview(mainHeaderView, at: 0)
        tableViewPlain.mainHeaderView = mainHeaderView
        
        tableViewPlain.contentInset = UIEdgeInsets(top: JKStatusBarHeight, left: 0, bottom: JKCurrentHomeIndicatorHeight, right: 0)
        tableViewPlain.contentOffset = CGPoint(x: 0, y: -tableViewPlain.contentInset.top)
        
        tableViewPlain.register(UINib(nibName: "JKNewsListCell", bundle: nil), forCellReuseIdentifier: "JKNewsListCell")
        tableViewPlain.register(JKHomeSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: "JKHomeSectionHeaderView")
        
        tableViewPlain.mj_header = MJRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadNewData))
        
        tableViewPlain.addFooterWithRefreshingTarget(target: self, refreshingAction: #selector(loadMoreData))
    }
    
    // MARK: - 加载数据
    
    override func loadNewData() {
        
        self.tableViewPlain.mj_footer.endRefreshing()
        refreshView.beginAnimating()
        
        JKNewsListGetDataModel.loadLatestData { (dict, error) in
            
            self.refreshView.stopAnimating()
            self.tableViewPlain.mj_header.endRefreshing()
            
            if error != nil || (dict?.allKeys.count ?? 0) < 4 {
                
                if self.todayStories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            self.hideReloadView()
            
            // 设置顶部轮播图数据
            let otherDataDicts = dict![JKTopStoryListKey] as! NSArray
            let imagUrls       = otherDataDicts.value(forKeyPath: "image") as! [String]
            let titles         = otherDataDicts.value(forKeyPath: "title") as! [String]
            
            self.mainHeaderView.setImageData(imageUrls: imagUrls, titles: titles, otherDataDicts: otherDataDicts as? [[String : AnyObject]])
            
            self.mainHeaderView.updateSkin()
            
            // 列表数据
            let latestStories = dict![JKStoryListModelKey] as! [JKNewsListModel]
            let latestDateStr = dict![JKStoryDateKey] as! String
            
            if self.todayStories.count > 0 &&
                self.loadedDate.count > 0 &&
                self.todayStories.count == latestStories.count &&
                self.todayDate == latestDateStr {
                
                return
            }
            
            self.todayStories = latestStories
            self.todayDate = latestDateStr
            
            self.stories.removeAll()
            self.loadedDate.removeAll()
            self.fmtDateArr.removeAll()
            
            self.stories.append(latestStories)
            self.loadedDate.append(latestDateStr)
            self.fmtDateArr.append(dict![JKStoryFmtDateKey] as! String)
            
            
            if (JKSQLiteManager.shared.reach.currentReachabilityStatus() == ReachableViaWiFi) {
            }
            // 自动离线还是放在这里吧
            if UserDefaults.standard.bool(forKey: JKAutoDownloadKey) && (JKSQLiteManager.shared.reach.currentReachabilityStatus() == ReachableViaWiFi) {
                
                if let arr = dict![JKStoryListDictKey] as? NSArray {
                    
                    let IDs = arr.value(forKeyPath: "id") as! [AnyObject]
                    
                    var ids = [String]()
                    
                    for obj in IDs {
                        
                        ids.append(String(describing: obj))
                    }
                    
                    JKSQLiteManager.cacheDetailWithIDs(IDs: ids)
                }
            }
            
            self.latestStoryCount = CGFloat(self.todayStories.count)
            
            self.tableViewPlain.reloadData()
            self.tableViewPlain.mj_footer.isHidden = false
            
            self.loadMoreData()
        }
    }
    
    override func loadMoreData() {
        
        self.tableViewPlain.mj_header.endRefreshing()
        self.refreshView.stopAnimating()
        
        JKNewsListGetDataModel.loadMoreDataWithDate(date: self.loadedDate.last!) { (dict, error) in
            
            self.tableViewPlain.mj_footer.endRefreshing()
            
            if error != nil {
                
                return
            }
            
            self.stories.append(dict![JKStoryListModelKey] as! [JKNewsListModel])
            self.loadedDate.append(dict![JKStoryDateKey] as! String)
            self.fmtDateArr.append(dict![JKStoryFmtDateKey] as! String)
            
            self.tableViewPlain.reloadData()
        }
    }
    
    override func navBackButtonClick() {
        
        let mainNav = self.navigationController as! JKMainNavigationController
        
        if mainNav.showLeftVcBlock != nil {
            
            mainNav.showLeftVcBlock!()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}

// MARK: - 3DTouch代理

extension JKHomeViewController: UIViewControllerPreviewingDelegate{
    
    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
        
        //        self.readNoticeLabel.hidden = YES
        
        // 1、获取sourceView
        if #available(iOS 9.0, *) {
            
            let sourceView = previewingContext.sourceView
            
            /**通过坐标点获取 indexPath */
            /*
             同样如果sourceView != self.tableView的话，也需要转换坐标系
             */
            let point = tableViewPlain.convert(location, from: sourceView)
            
            let indexP = tableViewPlain.indexPathForRow(at: point)
            
            // 如果indexPath为nil，则直接返回nil
            guard let indexPath = indexP else { return nil }
            
            /**获得当前cell */
            let cell = tableViewPlain.cellForRow(at: indexPath)
            
            // 设置sourceRect
            let sourceRect = cell?.frame
            
            /*
             这里同时也涉及到坐标系转换
             sourceRect = [self.tableView convertRect:cell.frame toView:sourceView];
             */
            previewingContext.sourceRect = sourceRect!
            
            let model = self.stories[indexPath.section][indexPath.row]
            
            let detailViewController = JKNewsDetailViewController()
            
            detailViewController.storyID = model.id
            detailViewController.stories = self.stories
            detailViewController.indexPath = indexPath
            detailViewController.storyListVc = self
            
            return detailViewController;
            
        } else {
            
            return nil
        }
    }
    
    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
        
        navigationController?.pushViewController(viewControllerToCommit, animated: true)
    }
}

// MARK: - tableView dataSource

extension JKHomeViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        return stories.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return (stories[section] as Array).count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "JKNewsListCell") as? JKNewsListCell
        
        if (cell == nil) {
            
            cell = JKNewsListCell(style: UITableViewCellStyle.default, reuseIdentifier: "JKNewsListCell")
        }
        
        let model = stories[indexPath.section][indexPath.row]
        
        model.alreadyRead = JKSQLiteManager.queryIsReadWithStoryID(storyID: model.id!)
        
        cell?.model = model
        
        return cell!
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return section == 0 ? 0 : JKSectionHeaderH
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let secHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: "JKHomeSectionHeaderView") as! JKHomeSectionHeaderView
        
        secHeader.headerTitle = fmtDateArr[section]
        
        return secHeader
    }
}

// MARK: - tableView delegate

extension JKHomeViewController {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
        
        let md = stories[indexPath.section][indexPath.row]
        
        let vc = JKNewsDetailViewController()
        
        vc.storyID = md.id
        vc.stories = self.stories
        vc.indexPath = indexPath
        vc.storyListVc = self
        
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - scrollView delegate
extension JKHomeViewController {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    
        self.readNoticeLabel.isHidden = true
        mainHeaderViewRemoveTimer()
    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        
    
        mainHeaderViewAddTimer()
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
    
        mainHeaderViewAddTimer()
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
    
        mainHeaderViewAddTimer()
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    
        mainHeaderViewAddTimer()
    }
    
    /** 添加轮播图定时器 */
    private func mainHeaderViewAddTimer() {
        
        if (tableViewPlain.contentOffset.y + 20 >= JKScreenW * 0.85 - 120 - 20) { return }
        mainHeaderView.addTimer()
    }
    
    private func mainHeaderViewRemoveTimer() {
        
        mainHeaderView.removeTimer()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if (scrollView.contentOffset.y <= -scrollView.contentInset.top) {

            tableViewPlain.contentOffset = CGPoint(x: 0, y: (tableViewPlain.contentOffset.y <= -140) ? -140 : tableViewPlain.contentOffset.y)
        }
        
        // 刷新控件的进度
        self.refreshView.progress = ((self.tableViewPlain.contentOffset.y < -self.tableViewPlain.contentInset.top && self.tableViewPlain.mj_header.state != MJRefreshState.refreshing)) ? -(self.tableViewPlain.contentOffset.y + self.self.tableViewPlain.contentInset.top) / 54.0 : 0
        
        statusBarView.isHidden = (scrollView.contentOffset.y < JKScreenW * 0.85 - 140)
        
        navBgView.alpha = ((scrollView.contentOffset.y + 20) / (JKScreenW * 0.85 - 120))
        
        if (scrollView.contentOffset.y + scrollView.contentInset.top) > (latestStoryCount * tableViewRowH + (JKScreenW * 0.85 - 140)) {

            self.navBgView.alpha = 0
        }
        
        self.navTitle = (scrollView.contentOffset.y + JKStatusBarHeight > (latestStoryCount) * tableViewRowH + (JKScreenW * 0.85 - 140)) ? "" : "今日热闻"
        //    NSLog(@"%.2f---%.2f---%.2f", self.navBarView.bgAlpha, scrollView.contentOffset.y + scrollView.contentInset.top, (([self.stories.firstObject count] - 1) * tableViewRowH + (JKScreenW * 0.85 - 140)))
        if (scrollView.contentOffset.y + scrollView.contentInset.top > JKScreenH) {
            return
        }
    
        // 顶部图片轮播控件的Y值
        mainHeaderView.y = -80 - (-scrollView.contentOffset.y - 20) * 0.5
    
        // 顶部图片轮播控件中的标题和pageControl的Y值
        var Y = (self.mainHeaderView.bounds.size.height-92 + (-scrollView.contentOffset.y - JKStatusBarHeight) * 0.5)
        Y+=(JKIsIphoneX ? 10 : 0)
        mainHeaderView.setPageControlY(Y: Y)
    }
}

// MARK: - 点击轮播图的代理
extension JKHomeViewController: JKRecycleViewDelegate{
    
    func recycleView(recycleView: JKRecycleView, didClickImageWithIndex: Int, otherDataDict: [String : AnyObject]) {
        
        if let _ = otherDataDict["error"] {
            return
        }
        
        JKLog(message: "index: \(didClickImageWithIndex)  otherDataDict: \(otherDataDict)")
        
        let vc = JKNewsDetailViewController()
        
        vc.storyID = String(format: "%@", otherDataDict["id"] as! CVarArg)
        vc.isTop = true
        vc.stories = self.stories
        vc.storyListVc = self
        
        var indexPath: IndexPath? = nil
        
        for i in 0 ..< self.stories.count {
            
            let arr = self.stories[i]
            
            for j in 0 ..< arr.count {
                
                let md = arr[j]
                
                if md.id == vc.storyID {
                    
                    indexPath = IndexPath(row: j, section: i)
                    
                    break
                }
            }
            
        }
        
        vc.indexPath = indexPath
        
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - 首页刷新进度圈

class JKHomeRefreshProgressView: UIView {
    
    /** 进度 */
    var progress: CGFloat {
        
        set{
            
            if (_progress == (newValue < 0.05 ? 0 : newValue) && newValue <= 0) {
                return
            }
            
            _progress = newValue
            
            setNeedsDisplay()
        }
        
        get{
            
            return _progress
        }
    }
    
    /** 进度 */
    private var _progress: CGFloat = 0
    
    /** 菊花开始旋转 */
    func beginAnimating() {
        
        progress = 0
        
        indicatorView.startAnimating()
    }
    
    /** 菊花停止旋转 */
    func stopAnimating() {
        
        indicatorView.stopAnimating()
    }
    
    // MARK: - 属性
    
    /** indicatorView */
    private lazy var indicatorView: UIActivityIndicatorView = {
        
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
        
        addSubview(indicatorView)
        
        return indicatorView
    }()
    
    // MARK: - 初始化
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initialization()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        initialization()
    }
    
    private func initialization() {
        
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        if _progress <= 0 { return }
        
        let center = CGPoint(x: rect.size.width * 0.5, y: rect.size.height * 0.5)
        
        //以下数字都是慢慢微调出来的~~
        let radius = rect.size.width > rect.size.height ? rect.size.height * 0.4 : rect.size.width * 0.4
        let startA = CGFloat.pi * 0.5
        let endA = startA + _progress * CGFloat.pi * 2
        
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startA, endAngle: endA, clockwise: true)
        
        path.lineWidth     = 1
        path.lineCapStyle  = CGLineCap.round
        path.lineJoinStyle = CGLineJoin.round
        
        JKSameRGBColor(217).set()
        
        path.stroke()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        indicatorView.center = CGPoint(x: self.width * 0.5, y: self.height * 0.5)
    }
}

// MARK: - 刷新为已读颜色

extension JKHomeViewController: JKStoryListReadProtocol{
    
    func reloadReadStoryWith(indexPath: IndexPath?) {
        
        guard let _ = indexPath else { return }
        
        if stories[0].count <= 0 { return }
        
        tableViewPlain.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.none)
    }
    
    /** 针对3DTouch跳转返回后 刷新已读字体颜色 */
    public func reload3DTouchReadWithID(storyID: String?) {
        
        DispatchQueue.main.afterSeconds(time: 1) {
            
            if self.stories.count <= 0 || self.stories[0].count <= 0 || storyID == nil { return }
            
            let count = self.stories[0].count
            
            for i in 0 ..< count {
                
                let md = self.stories[0][i]
                
                if (md.id != storyID!) { continue }
                
                let indexPath = IndexPath(row: i, section: 0)
                
                self.tableViewPlain.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none)
                
                break
            }
        }
    }
}

// MARK: - 更新皮肤

extension JKHomeViewController {
    
    override func updateSkin() {
        
        if vcSkinModel == currentSkinModel {
            return
        }
        
        super.updateSkin()
        
        self.mainHeaderView.updateSkin()
        
        self.statusBarView.backgroundColor = self.navBgView.backgroundColor
        
        self.tableViewPlain.mj_footer.backgroundColor = UIColor.clear
    }
}
